package com.iteaj.iot.client;

import com.iteaj.network.*;
import com.iteaj.network.client.ClientComponent;
import com.iteaj.network.client.ClientMessage;
import com.iteaj.network.client.IotClient;
import com.iteaj.network.codec.IotMessageDecoder;
import com.iteaj.network.config.ConnectProperties;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import org.springframework.core.GenericTypeResolver;

/**
 * 此适配器可以自定义实现各个组件的实现细节
 * @param <M>
 */
public abstract class TcpClientComponentAdapter<M extends ClientMessage> extends TcpSocketClient
        implements IotProtocolFactory<M>, ClientComponent<M> {

    private ProtocolFactory<M> delegation;

    public TcpClientComponentAdapter(ConnectProperties config) {
        super(config);
        this.setClientComponent(this);
        this.delegation = new ProtocolFactoryDelegation(this);
        this.delegation.setDelegation(new ProtocolTimeoutStorage(getName()));
    }

    @Override
    public abstract String getName();

    @Override
    public AbstractProtocol get(String key) {
        return delegation.get(key);
    }

    @Override
    public AbstractProtocol add(String key, Protocol val) {
        return delegation.add(key, val);
    }

    @Override
    public AbstractProtocol add(String key, Protocol protocol, long timeout) {
        return delegation.add(key, protocol, timeout);
    }

    @Override
    public AbstractProtocol remove(String key) {
        return delegation.remove(key);
    }

    @Override
    public boolean isExists(String key) {
        return delegation.isExists(key);
    }

    @Override
    public Object getStorage() {
        return delegation.getStorage();
    }

    @Override
    protected abstract IotMessageDecoder getClientProtocolDecoder();

    @Override
    public String getDesc() {
        return "Tcp客户端组件("+this.getClass().getSimpleName()+")";
    }

    @Override
    public void init(Object... args) {
        super.init((NioEventLoopGroup) args[0]);
    }

    @Override
    public IotClient getClient() {
        return this;
    }

    @Override
    public IotProtocolFactory protocolFactory() {
        return this.delegation;
    }

}
